<template>
  <div style="width: 50%;border: 1px solid;">
    <div class="card" style="padding: 25px 30px;background: linear-gradient(to bottom, #f5f3f2, #92bdce);">
      <div style="font-size: 20px;color: red;display: flex;align-items: center;justify-content: center">
        <span style="margin-bottom: 20px">个人密码修改</span>
      </div>
      <el-form :model="data.user" ref="formRef" :rules="data.rules" label-width="100px" style="padding-right: 50px">
        <el-form-item prop="password" label="原密码">
          <el-input :prefix-icon="Lock" v-model="data.user.password" show-password />
        </el-form-item>
        <el-form-item prop="newPassword" label="新密码">
          <el-input :prefix-icon="Lock" v-model="data.user.newPassword" show-password />
        </el-form-item>
        <el-form-item prop="confirmPassword" label="确认新密码">
          <el-input :prefix-icon="Lock" v-model="data.user.confirmPassword" show-password />
        </el-form-item>
        <div style="text-align: center;margin-top: 20px">
          <el-button style="padding: 10px 25px" type="primary" @click="updatePassword">更 新 密 码</el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import {reactive, ref} from "vue"
import {ElMessage} from "element-plus";
import router from "@/router";
import {Lock} from "@element-plus/icons-vue";
import alovaInstance from "@/utils/request.js";

const data = reactive({
  user: JSON.parse(localStorage.getItem('credit-system-user') || '{}'),
  rules: {
    password: [
      {required: true, message: '原密码不能为空', trigger: 'blur'},
    ],
    newPassword: [
      {required: true, message: '新密码不能为空', trigger: 'blur'},
    ],
    confirmPassword: [
      {required: true, message: '请再次输入新密码', trigger: 'blur'},
    ]
  },
})

const formRef = ref()

// 把当前修改的用户信息存储到后台数据库
const updatePassword = () => {
  formRef.value.validate((valid =>{
    if (valid) {
      if (data.user.newPassword !== data.user.confirmPassword) {
        ElMessage.error('两次密码不一致')
        return
      }
      alovaInstance.Put('/manager/updatePassword', data.user).then(res => {
        if (res.code === '200') {
          ElMessage.success('修改密码成功')
          // 清空缓存
          localStorage.removeItem('credit-system-user')
          router.push('/studentLogin')
        }/* else {
          ElMessage.error(res.message || '修改密码失败')
        }*/
      }).catch(error => {
        console.error('请求失败:', error);
        ElMessage.error(error.message || '网络错误，请稍后重试');
      });
    }
  }))
}
</script>